<!--
 * @Descripttion: 
 * @version: 
 * @Author: gonghong
 * @Date: 2023-07-05 13:46:15
-->
<script setup>
import { reactive, getCurrentInstance, ref } from "vue";
import { onShow, onLoad, onUnload } from "@dcloudio/uni-app";
import {
  combo,
  findAllTreeInfoList,
  UPLOAD_FILE_URL,
  saveInstallWorkOrder,
  getFactoryTypeList,
  findValveList,
  getUserInfoByPhoneNo,
  getDeviceInfoByDeviceCode,
  getDeviceInfoByDeviceImie,
} from "@/api/system";
import { batchUpload } from "@/homePages/common/batchUpload";
import { matchFilePath } from "@/common/utils";

const instance = getCurrentInstance();

const eventChannel = instance.proxy.getOpenerEventChannel();

// 默认用户类型
const DEFAULT_USER_TYPE = "民用";
//创建类型，false为新增，true为编辑
const createdType = ref(false);

const isSumitting = ref(false);

const addresData = reactive([]);
const DEVICE_TYPE_LIST = ref([]);
const FACTORY_TYPE_LIST = ref([]);
const DETECTION_TYPE_LIST = ref([]);
const USER_TYPE_LIST = ref([]);
const DEVICE_POS_LIST = ref([]);
const valveTypeList = ref([]);

const deviceParams = reactive({
  imei: null,
  //设备编码
  deviceCode: null,
  //设备名称
  deviceName: null,
  //设备类型
  deviceType: null,
  //设备类型
  factoryCode: null,
  // 出场时间
  deliveryTime: null,
  //监测类型
  detectionType: null,
  valveModel: null,
  valveName: null,
  valveCode: null,
  valveId: null,
  valveInstallationPosition: null,
  //用户手机号
  phoneNo: null,
  userName: null,
  userNum: null,
  backupPhone: null,

  addr: null,
  userType: null,
  cityId: null,
  areaId: null,
  buildId: null,
  unitId: null,
  addersId: null,
  id: null,
  //安装位置
  installationPosition: null,
  //备注说明
  content: null,
  uploadFiles: [],
});

const normalizeText = (data) =>
  data.map((item) => ({ ...item, text: item.name })) || [];

const initData = async () => {
  uni.showLoading({ title: "加载中...", mask: true });
  const result = await combo({
    codeTypes: "DEVICE_TYPE,DETECTION_TYPE,USER_TYPE,DEVICE_POS",
  });

  const resultData = result.data || {};
  DEVICE_TYPE_LIST.value = normalizeText(resultData.DEVICE_TYPE);

  DETECTION_TYPE_LIST.value = normalizeText(resultData.DETECTION_TYPE);

  USER_TYPE_LIST.value = normalizeText(resultData.USER_TYPE);
  const defaultUserType = USER_TYPE_LIST.value.find(
    ({ name }) => name === DEFAULT_USER_TYPE
  );
  deviceParams.userType = (defaultUserType && defaultUserType.value) || "";

  DEVICE_POS_LIST.value = normalizeText(resultData.DEVICE_POS);

  const addrResult = await findAllTreeInfoList({ level: 4 });
  const addrResultData = addrResult.data || [];
  addresData.length = 0;
  addresData.push(...addrResultData);

  const factoryResult = await getFactoryTypeList();
  if (factoryResult.code === 200) {
    FACTORY_TYPE_LIST.value = factoryResult.data || [];
    FACTORY_TYPE_LIST.value.map((item) => {
      item.text = item.factoryName;
      item.value = item.factoryCode;
      return item;
    });
  }
  const vavleResult = await findValveList({});
  if (vavleResult.code === 200) {
    valveTypeList.value = vavleResult.data || [];
    valveTypeList.value.map((item) => {
      item.text = item.deviceName;
      item.value = item.deviceCode;
      return item;
    });
  }
  uni.hideLoading();
};
initData();
onLoad(async (option) => {
  if (!eventChannel || !eventChannel.on) {
    return;
  }
  console.log(option)
  if(option.imei){
	  deviceParams.deviceCode = option.imei
  }
  //接受事件传递的参数对象
  eventChannel.on("getData", (data) => {
    if (data) {
      createdType.value = true;
    }
    Object.keys(deviceParams).map((key) => {
      if (data[key]) {
        deviceParams[key] = data[key];
      }
    });
    //上传照片回显
    if (data.filePath && data.filePath.length > 0) {
      const urlArr = data.filePath.split(",");
      deviceParams.uploadFiles.length = 0;
      const fileList = [];
      urlArr.map((filePath) => {
        fileList.push(matchFilePath(filePath));
      });
      deviceParams.uploadFiles = fileList;
      console.log(deviceParams.uploadFiles, "上传图片回显");
    }

    //用户地址回填数据
    setAddresId();
  });
});

onUnload(() => {
  if (eventChannel && eventChannel.off) {
    eventChannel.off();
  }
});

const getFactoryCodeByName = (name) => {
  var ret = "";
  FACTORY_TYPE_LIST.value.forEach((item) => {
    if (item.text === name) {
      ret = item.value;
    }
  });
  return ret;
};

/**
 * @function: 扫一扫
 * @return {*}
 */
const link = () => {
  uni.scanCode({
    success: function (res) {
      console.log(22222, res, res.result)
      //成功
      if (res.result) {
        deviceParams.imei = res.result.split(";")[0];
        console.log(33333, deviceParams.imei)
        searchDeviceInfo(false);
        this.createdType = true;
      }
    },
    fail(res) {
      showToast("二维码信息获取失败");
    },
  });
};

const addrOnchange = (e) => {
  const arr = e.detail.value || [];
  deviceParams.cityId = arr[0]?.value;
  deviceParams.areaId = arr[1]?.value;
  deviceParams.buildId = arr[2]?.value;
  deviceParams.unitId = arr[3]?.value;
};

const setAddresId = () => {
  if (deviceParams.unitId) {
    deviceParams.addersId = deviceParams.unitId;
    return;
  }
  if (deviceParams.buildId) {
    deviceParams.addersId = deviceParams.buildId;
    return;
  }
  if (deviceParams.areaId) {
    deviceParams.addersId = deviceParams.areaId;
    return;
  }
  if (deviceParams.cityId) {
    deviceParams.addersId = deviceParams.cityId;
    return;
  }
};

const uploadFileSelect = (e) => {
  const tempFilePaths = e.tempFilePaths;
  tempFilePaths.map((filePath) => {
    batchUpload(
      {
        uploadUrl: UPLOAD_FILE_URL,
        filePath: filePath,
      },
      null,
      (data) => {
        setUploadImg(data);
      },
      (error) => {
        showToast("上传失败!");
        removeSavedFile();
      },
      (completeRes) => {
        if (completeRes.statusCode === 413) {
          showToast("上传失败!");
          removeSavedFile();
        }
      }
    );
  });
};

const setUploadImg = (data) => {
  console.log(222222,data)
  deviceParams.uploadFiles.push(matchFilePath(data));
};

/**
 * @function  强制刷新上传数据，解决上传组件失败依然展示图片的本地路径问题.
 * @return {*}
 */
const removeSavedFile = () => {
  deviceParams.uploadFiles = JSON.parse(
    JSON.stringify(deviceParams.uploadFiles)
  );
};

const isSubmitting = ref(false); // 用于控制按钮是否可点击

const submitOnClick = (installationStatus) => {
  if (!deviceParams.deviceCode || deviceParams.deviceCode.length <= 0) {
    showToast("设备编码不能为空");
    return;
  }
  if (!deviceParams.deviceName || deviceParams.deviceName.length <= 0) {
    showToast("设备名称不能为空");
    return;
  }
  if (!deviceParams.deviceType || deviceParams.deviceType.length <= 0) {
    showToast("设备类型不能为空");
    return;
  }
  if (!deviceParams.factoryCode || deviceParams.factoryCode.length <= 0) {
    showToast("设备厂家不能为空");
    return;
  }
  if (!deviceParams.detectionType || deviceParams.detectionType.length <= 0) {
    showToast("监测类型不能为空");
    return;
  }

  if (!deviceParams.phoneNo || deviceParams.phoneNo.length <= 0) {
    showToast("用户手机号不能为空");
    return;
  }
  if (!isPhoneNum(deviceParams.phoneNo)) {
    return;
  }
  if (deviceParams.backupPhone && !isPhoneNum(deviceParams.backupPhone)) {
    return;
  }
  if (!deviceParams.cityId || deviceParams.cityId.length <= 0) {
    showToast("用户地址不能为空");
    return;
  }
  if (!deviceParams.userType) {
    showToast("用户类型不能为空");
    return;
  }
  // if(!deviceParams.addr||deviceParams.addr.length<=0){
  //     showToast('用户详细地址不能为空')
  //     return
  // }
  //   if (!deviceParams.installationPosition || deviceParams.installationPosition.length <= 0) {
  //     showToast('设备安装位置不能为空')
  //     return
  //   }

  if (installationStatus === 1) {
    if (deviceParams.uploadFiles.length <= 0) {
      showToast("设备安装图片不能为空");
      //showToast(deviceParams.uploadFiles);
      //showToast(deviceParams.uploadFiles.length);
      return;
    }
  }
  console.log(2222, deviceParams.uploadFiles)
  const filePath = deviceParams.uploadFiles.map((item) => {
    console.log(1111, item)
    return item.url;
  });
  
  const params = {
    ...deviceParams,
    installationStatus: installationStatus,
    filePath: filePath.length > 0 ? filePath.join(",") : "",
  };
  if(!isSumitting.value){
    isSumitting.value = true;
  }else{
    return;
  }
  uni.showLoading({ title: '正在安装中', mask: true })
  saveInstallWorkOrder(params).then((result) => {
    console.log("saveInstallWorkOrder")
    uni.hideLoading();
    isSumitting.value = false;
    if (result.code == 200) {
      showToast(result.msg);
      uni.navigateBack();
    }
    isSubmitting.value = false; // 请求完成后重置提交状态
  }).catch((err) => {
    uni.hideLoading();
    showToast(err);// 抛错
    isSubmitting.value = false; // 请求完成后重置提交状态
  });
};
const showToast = (msg) => {
  uni.showToast({
    title: msg,
    icon: "none",
    duration: 2000,
    mask: true,
  });
};

const iconUserClick = async () => {
  if (!isPhoneNum(deviceParams.phoneNo)) {
    return;
  }

  uni.showLoading({ title: "用户信息获取中...", mask: true });
  const result = await getUserInfoByPhoneNo({
    phoneNo: deviceParams.phoneNo,
  });
  uni.hideLoading();

  if (result.code == 200) {
    const {
      userType = null,
      addr = null,
      cityId = null,
      areaId = null,
      buildId = null,
      unitId = null,
      userName = null,
      userNum = null,
      backupPhone = null,
    } = result.data || {};
    //回填用户类型
    if (userType) {
      deviceParams.userType = userType.toString();
    }
    //回填详细地址
    if (addr) {
      deviceParams.addr = addr;
    }
    if (cityId) {
      deviceParams.cityId = cityId;
      deviceParams.addersId = cityId;
    }
    if (areaId) {
      deviceParams.areaId = areaId;
      deviceParams.addersId = areaId;
    }
    if (buildId) {
      deviceParams.buildId = buildId;
      deviceParams.addersId = buildId;
    }
    if (unitId) {
      deviceParams.buildId = unitId;
      deviceParams.addersId = unitId;
    }
    if (userName) {
      deviceParams.userName = userName;
    }
    if (userNum) {
      deviceParams.userNum = userNum;
    }
    if (backupPhone) {
      deviceParams.backupPhone = backupPhone;
    }
  } else {
    showToast("用户信息获取失败，请手动输入!");
  }
};

// ById:根据设备id查找

const searchDeviceInfo = async (ById) => {
  // if (!deviceParams.deviceCode) {
  //   return;
  // }
  // if (deviceParams.deviceCode.length <= 0) {
  //   return;
  // }
  uni.showLoading({ title: "查询中...", mask: true });
  let result;
  console.log("查询中...")
  if(ById){
    console.log("查询中id...")
    result = await getDeviceInfoByDeviceCode({
      deviceCode: deviceParams.deviceCode,
    });
  }else{

    console.log("查询中Imie")
    console.log(deviceParams.imei)
    result = await getDeviceInfoByDeviceImie({
      imei: deviceParams.imei,
    });
    console.log("查询中Imie", result)
  }
  uni.hideLoading();

  if (result.code == 200) {
    const {
      deviceCode = null,
      deviceName = null,
      deviceType = null,
      factoryCode = null,
      factoryName = null,
      detectionType = null,
      deliveryTime = null,
    } = result.data || {};
    //回填设备名称
    if (deviceName) {
      deviceParams.deviceName = deviceName;
    }
    if (deviceCode) {
      deviceParams.deviceCode = deviceCode;
    }
    //回填设备类型
    if (deviceType) {
      deviceParams.deviceType = deviceType;
    }
    //回填厂家
    deviceParams.factoryCode = factoryCode || getFactoryCodeByName(factoryName);

    if (deliveryTime) {
      deviceParams.deliveryTime = deliveryTime;
    }

    deviceParams.detectionType =
      detectionType || DETECTION_TYPE_LIST.value[0].value;
  } else {
    showToast("设备信息获取失败，请手动输入!");
  }
};

const valveOnChange = (val) => {
  const {
    deviceModel = null,
    deviceName = null,
    id = null,
  } = findValveItem(val);
  deviceParams.valveModel = deviceModel;
  deviceParams.valveName = deviceName;
  deviceParams.valveId = id;
};

const findValveItem = (val) => {
  let valveItem = {};
  valveTypeList.value.map((item) => {
    if (item.deviceCode == val) {
      valveItem = item;
    }
  });
  return valveItem;
};

const isPhoneNum = (phoneNumber) => {
  const phoneNumberRegex = /^1[3456789]\d{9}$/;
  if (phoneNumberRegex.test(phoneNumber)) {
    return true;
  } else {
    showToast("手机号格式错误!");
    return false;
  }
};

const modifyAddress = () => {
  uni.getSystemInfo({
    success: (res) => {
      if (!res.locationEnabled || !res.locationAuthorized) {
        uni.showToast({
          title: "请确保手机系统定位已开启",
          icon: "none",
          duration: 2000,
        });
      } else {
        authorize();
      }
    },
  });
};
const authorize = () => {
  uni.authorize({
    scope: "scope.userLocation",
    success() {
      uni.chooseLocation({
        success: function (res) {
          console.log(res.address); // 详细地址
          uni.showToast({
            title: res.address,
            icon: "none",
            duration: 2000,
          });

          adjustLocation(res.address + res.name); //转化为对应的市  区县   街道   单元
          deviceParams.addr = res.name;
          //设置表格组件的
          setAddresId();
        },
        fail: function (error) {
          console.log(error);
        },
      });
    },
    fail() {
      uni.showToast({
        title: "请设置授权应用获取位置信息",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

const adjustLocation = (address) => {
  deviceParams.cityId = "";
  deviceParams.areaId = "";
  deviceParams.buildId = "";
  deviceParams.unitId = "";

  var level = 0;
  deviceParams.cityId = addresData[0].id;

  level++;
  var childrens = addresData[0].children;
  for (let index = 0; index < childrens.length; index++) {
    let str = childrens[index].label;

    if (address.indexOf(str) > -1) {
      //找到了市县
      deviceParams.areaId = childrens[index].id;

      level++;
      var areaChildrens = childrens[index].children;
      for (let index1 = 0; index1 < areaChildrens.length; index1++) {
        str = areaChildrens[index1].label;

        if (address.indexOf(str) > -1) {
          //如果建筑选中
          //找到了建筑
          deviceParams.buildId = areaChildrens[index1].id;

          level++;
          var buildChildrens = areaChildrens[index1].children;
          for (let index2 = 0; index2 < buildChildrens.length; index2++) {
            str = buildChildrens[index2].label;

            if (address.indexOf(str) > -1) {
              //如果小区选中

              deviceParams.unitId = buildChildrens[index2].id;
              level++;
            }
          }
        }
      }
    }
  }
};
</script>
<template>
  <view class="container">
    <uni-section title="设备信息" type="line">
      <cell-list title="设备编码" :required="true">
        <view class="f-df f-ai-c">
          <uni-easyinput
            placeholder="请输入内容"
            :inputBorder="false"
            v-model="deviceParams.deviceCode"
            :clearable="false"
            :disabled="createdType"
            @blur="searchDeviceInfo(true)"
          />
          <text
            class="iconfont icon-saoyisao"
            @tap.stop="link"
            v-show="!createdType"
          ></text>
        </view>
      </cell-list>
      <cell-list title="设备名称" :required="true">
        <uni-easyinput
          placeholder="请输入内容"
          :inputBorder="false"
          v-model="deviceParams.deviceName"
          :clearable="false"
          :disabled="createdType"
        />
      </cell-list>
      <cell-list title="设备类型" :required="true">
        <uni-data-select
          :localdata="DEVICE_TYPE_LIST"
          v-model="deviceParams.deviceType"
        />
      </cell-list>
      <cell-list title="设备厂家" :required="true">
        <uni-data-select
          :localdata="FACTORY_TYPE_LIST"
          v-model="deviceParams.factoryCode"
        />
      </cell-list>
      <cell-list title="监测类型" :required="true">
        <uni-data-select
          :localdata="DETECTION_TYPE_LIST"
          v-model="deviceParams.detectionType"
        />
      </cell-list>
    </uni-section>
    <!-- <uni-section title="阀门信息" type="line">
            <cell-list title="阀门名称">
                <uni-data-select
                    :localdata="valveTypeList"
                    v-model="deviceParams.valveCode"
                    @change="valveOnChange"
                />
            </cell-list>
            <cell-list title="阀门位置">
                <uni-data-select
                    :localdata="DEVICE_POS_LIST"
                    v-model="deviceParams.valveInstallationPosition"
                />
            </cell-list>
        </uni-section> -->
    <uni-section title="用户信息" type="line">
      <cell-list title="手机号" :required="true">
        <uni-easyinput
          placeholder="请输入内容"
          :inputBorder="false"
          v-model="deviceParams.phoneNo"
          suffixIcon="search"
          @iconClick="iconUserClick"
          :disabled="createdType"
        />
      </cell-list>
      <cell-list title="备用手机">
        <uni-easyinput
          v-model="deviceParams.backupPhone"
          placeholder="请输入备用手机"
          :inputBorder="false"
          :disabled="createdType"
        />
      </cell-list>
      <cell-list title="用户号" :required="true">
        <uni-easyinput
          placeholder="请输入用户号"
          :inputBorder="false"
          :maxlength="10"
          v-model="deviceParams.userNum"
        />
      </cell-list>
      <cell-list title="用户名" :required="true">
        <uni-easyinput
          placeholder="请输入用户名"
          :inputBorder="false"
          :maxlength="10"
          v-model="deviceParams.userName"
        />
      </cell-list>
      <cell-list title="用户类型">
        <uni-data-select
          :localdata="USER_TYPE_LIST"
          :clearable="false"
          v-model="deviceParams.userType"
        />
      </cell-list>
      <cell-list title="安装位置">
        <uni-data-select
          :localdata="DEVICE_POS_LIST"
          v-model="deviceParams.installationPosition"
        />
      </cell-list>
      
      <cell-list
        title="地址"
        :showArrow="true"
        :required="true"
        style="position: relative"
      >
        <song-data-picker
          :openSearch="true"
          v-model="deviceParams.addersId"
          placeholder="请选择地址"
          popup-title="请选择地址"
          :localdata="addresData"
          :map="{ text: 'label', value: 'id' }"
          @change="addrOnchange"
        ></song-data-picker>
        <text
          class="iconfont icon-ditu map"
          @tap.stop="modifyAddress"
        ></text>
      </cell-list>
      <cell-list title="详细地址">
        <uni-easyinput
          placeholder="例:808号"
          :inputBorder="false"
          v-model="deviceParams.addr"
        />
      </cell-list>
    </uni-section>
    <uni-section title="安装图片" type="line">
      <view class="example-body">
        <uni-file-picker
          limit="3"
          title="最多选择3张图片"
          :auto-upload="false"
          v-model="deviceParams.uploadFiles"
          @select="uploadFileSelect"
        />
      </view>
    </uni-section>
    <uni-section title="备注说明" type="line">
      <view style="padding: 10px">
        <uni-easyinput
          type="textarea"
          placeholder="请输入内容"
          v-model="deviceParams.content"
        />
      </view>
    </uni-section>
    <view class="submitBox">
      <view class="warningBtn saveBtn" @click="submitOnClick(0)">
        <text>暂存</text>
      </view>
      <view class="primaryBtn" @click="submitOnClick(1)"
        disabled="isSubmitting"
      >
        <text>完成安装</text>
      </view>
    </view>
  </view>
</template>
<style lang="scss" scoped>
::v-deep .uni-forms-item {
  padding-left: 10px;
  padding-right: 10px;
  margin-bottom: 0;
  border-bottom: 1px solid #c8c7cc;
  font-size: 14px;
  color: #3b4144;
}
.example-body {
  padding: 10px;
  padding-top: 0;
}

.submitBox {
  display: flex;
  justify-content: flex-end;
  padding: 20upx;
  .saveBtn {
    margin-right: 32upx;
  }
}

::v-deep .uni-data-tree {
  .input-value-border {
    border: none;
  }
  .arrow-area {
    display: none !important;
  }
}

.map {
  position: absolute;
  right: 5px;
  top: 15px;
}

::v-deep .uni-select {
  border: none;
  border-bottom: none;
}
</style>
